<template>
  <div class="app-container">


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          style="margin-left: 10px;"
          @click="handleSelect"
          v-hasPermi="['mrp:mrpLine:add']"
          v-if="optType !== 'view'"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="mrpLineList"
        border
        @selection-change="handleSelectionChange"
        @cell-mouse-enter="handleCellEnter()"
        @cell-mouse-leave="handleCellLeave()">
      <el-table-column label="产品物料编码" align="center" prop="itemCode" />
      <el-table-column label="产品物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="计划数量" align="center" prop="quantity" />
      <el-table-column label="可用库存数量" align="center" prop="availableInventoryQuantity" v-if="computationRule === 'Y'" />
      <el-table-column label="需求数量" align="center" prop="requiredQuantity">
        <div class="requiredQuantityItem" slot-scope="scope">
          <el-input
              class="item_input"
              v-model="scope.row.requiredQuantity"
              size="mini"
              style="width: 100%;"
              :title="scope.row.requiredQuantity"
              @blur="handleRequiredQuantityBlur(scope.row)"
              v-if="optType !== 'view' && computationRule === 'Y'"
          />
          <el-input
              class="item_input"
              v-model="scope.row.requiredQuantity"
              size="mini"
              style="width: 100%;"
              :title="scope.row.requiredQuantity"
              readonly
              v-if="computationRule === 'N'"
          />
        </div>
      </el-table-column>
      <el-table-column label="BOM版本" align="center" prop="bomName">
        <template slot-scope="scope">
          <el-select
              v-model="scope.row.bomName"
              placeholder="请选择BOM"
              style="width:100%"
              @focus="handleBomSelectFocus(scope.row)"
              @change="(value) => handleBomSelectChange(value, scope.row)"
          >
            <el-option
                v-for="item in bomOptions"
                :key="item.bomId"
                :label="item.bomName"
                :value="item.bomCode"
                :disabled="optType === 'view'"
            >
              <div style="display: flex; justify-content: space-between; width: 100%;">
                <span>{{ item.bomName }}</span>
                <span style="color: #999; font-size: 12px; margin-left: 10px;">{{ item.bomCode }}</span>
                <span style="color: #999; font-size: 12px; margin-left: 10px;">{{ item.remark ? '备注:' + item.remark : '' }}</span>
                <span style="color: #999; font-size: 12px; margin-left: 10px;">{{ item.routeName ? '工艺路线:' + item.routeName : '' }}</span>
              </div>
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="optType !== 'view'">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mrp:mrpLine:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 销售预测计划产品选择 -->
    <PlanLineSelect
      ref="planLineSelect"
      @onSelected="onPlanLineSelected"
      :itemOrProduct="itemOrProduct"
    ></PlanLineSelect>


  </div>
</template>

<script>
import {
  listMrpLine,
  getMrpLine,
  delMrpLine,
  addMrpLine,
  updateMrpLine,
  addMrpLineBatch,
  updateMrpLineBatch
} from "@/api/mes/mrp/mrpLine";
import PlanLineSelect from "./multi";
import { listByCode } from "@/api/mes/md/bomgl";

export default {
  name: "MrpLine",
  components: { PlanLineSelect },
  props: {
    optType: null,
    mrpId: null,
    computationRule: null,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料需求计划（MRP）产品表格数据
      mrpLineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mrpId: this.mrpId,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantity: null,
        availableInventoryQuantity: null,
        requiredQuantity: null,
        bomId: null,
        bomCode: null,
        bomName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bomId: [
          { required: true, message: "BOM不能为空", trigger: "change" }
        ],
        requiredQuantity: [
          { required: true, message: "需求数量不能为空", trigger: "blur" }
        ],
      },
      // 选择计划产品类型
      itemOrProduct: 'PRODUCT',
      // 可修改单元格属性
      editProp: ['requiredQuantity'],
      // bom下拉框数据
      bomOptions: [],
      // 原BOM名称
      originalBomName: null,

    };
  },
  watch: {
    mrpId: function (newVal, oldVal) {
      if (newVal !== null && newVal !== oldVal) {
        this.queryParams.mrpId = newVal;
        this.getList();
      }
    },
    computationRule: function (newVal, oldVal) {
      if (newVal !== oldVal) {
        if (newVal === 'N' && oldVal === 'Y') {
          this.handleComputationRuleChange();
        }
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物料需求计划（MRP）产品列表 */
    getList() {
      this.loading = true;
      this.queryParams.mrpId = this.mrpId;
      listMrpLine(this.queryParams).then(response => {
        this.mrpLineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        mrpId: this.mrpId,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantity: null,
        availableInventoryQuantity: null,
        requiredQuantity: null,
        bomId: null,
        bomCode: null,
        bomName: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料需求计划（MRP）产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids
      getMrpLine(lineId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料需求计划（MRP）产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lineId != null) {
            updateMrpLine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMrpLine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.lineId || this.ids;
      this.$modal.confirm('是否确认删除物料需求计划（MRP）产品编号为"' + row.itemCode + '"的数据项？').then(function() {
        return delMrpLine(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mrp/mrpLine/export', {
        ...this.queryParams
      }, `mrpLine_${new Date().getTime()}.xlsx`)
    },
    // 打开销售计划产品选择框
    handleSelect() {
      this.$refs.planLineSelect.showFlag = true;
    },
    // 选择销售计划产品回调
    onPlanLineSelected(rows) {
      const list = [];
      rows.forEach(row => {
        // 查找是否已存在相同itemCode的物料
        const existingItem = list.find(item => item.itemCode === row.itemCode);
        if (existingItem) {
          // 如果存在相同itemCode的物料，合并数量
          existingItem.quantity = (parseFloat(existingItem.quantity) || 0) + (parseFloat(row.quantity) || 0);
        } else {
          // 如果不存在相同itemCode的物料，直接添加到列表
          list.push({
            ...row,
            mrpId: this.mrpId
          });
        }
      });

      if (list.length > 0) {
        addMrpLineBatch(list).then(response => {
          this.$modal.msgSuccess("添加成功");
          this.getList();
        })
      }

    },
    // 列表单元格鼠标进入事件
    handleCellEnter (row, column, cell, event) {
      if (column) {
        const property = column.property
        if (this.editProp.includes(property)) {
          cell.querySelector('.item_input').style.display = 'block'
        }
      }
    },
    // 列表单元格鼠标离开事件
    handleCellLeave (row, column, cell, event) {
      if (column) {
        const property = column.property
        if (this.editProp.includes(property)) {
          cell.querySelector('.item_input').style.display = 'none'
        }
      }
    },
    // 需求数量输入框失去焦点事件
    handleRequiredQuantityBlur(row) {
      const requiredQuantity = parseFloat(row.requiredQuantity)
      // 检查是否为有效数字
      if (isNaN(requiredQuantity)) {
        this.$modal.msgError("请输入有效数字");
        this.getList();
        return;
      }

      // 如果计算规则为Y，则执行计算逻辑
      if (this.computationRule === 'Y') {
        const differenceValue = row.quantity - row.availableInventoryQuantity <= 0 ? 0 : row.quantity - row.availableInventoryQuantity
        if (requiredQuantity < differenceValue) {
          this.$modal.msgError("需求数量不能小于" + differenceValue);
          this.getList();
          return;
        }
      }

      // 检查是否为负数
      if (requiredQuantity < 0) {
        this.$modal.msgError("需求数量必须大于等于0");
        this.getList();
        return;
      }

      // 检查是否超过计划数量
      if (requiredQuantity > row.quantity) {
        this.$modal.msgError("需求数量不能超过计划数量(" + row.quantity + ")");
        this.getList();
        return;
      }

      // 检查小数位数是否超过两位
      if (!/^\d+(\.\d{1,2})?$/.test(requiredQuantity.toString())) {
        this.$modal.msgError("需求数量最多只能有两位小数");
        this.getList();
        return;
      }

      // 修改需求数量
      updateMrpLine(row).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      })

    },
    // BOM下拉框聚焦事件
    handleBomSelectFocus(row) {
      this.bomOptions = [];
      this.originalBomName = row.bomName;
      listByCode(row.itemCode).then(response => {
        this.bomOptions = response.data;
      }).catch(e => {
        this.$modal.msgError("获取BOM列表失败");
        this.bomOptions = [];
      })
    },
    // BOM下拉框选择变化事件
    handleBomSelectChange(value, row) {
      // 查找选中的BOM对象
      const selectedBom = this.bomOptions.find(item => item.bomCode === value);

      if (selectedBom) {
        // 更新行数据中的BOM相关信息
        row.bomId = selectedBom.bomId;
        row.bomCode = selectedBom.bomCode;
        row.bomName = selectedBom.bomName;
      }

      if (!row.lineId) {
        this.$modal.msgWarning("请先保存该条数据");
        return;
      }
      // 更新行数据
      updateMrpLine(row).then(response => {
        this.$modal.msgSuccess("保存成功");
        this.getList();
      }).catch(error => {
        this.$modal.msgError("保存失败");
      });
    },
    // 计算规则修改
    handleComputationRuleChange() {
      updateMrpLineBatch(this.mrpLineList).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      }).catch(error => {
        this.$modal.msgError("修改失败");
        this.getList();
      });
    },



  }
};
</script>
